#include <ESP8266WiFi.h>
#define BUILTIN_LED 2
char P_NAME[] = "Codemao-Office";
char P_PSWD[] = "2<3]OzU(!h";

const char *ssid = P_NAME;
const char *password = P_PSWD;
const char *tcp_server = "creation-hardware.codemao.cn";
String reStr;
WiFiClient espClient;
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi()
{
  delay(10);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
  }
  randomSeed(micros());
}

void callback(byte *payload, unsigned int length)
{
  for (int i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]);
  }
  Serial.println();
}

void setup()
{
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);

  Serial.println("\n##################################");
  Serial.println(F("ESP32 Information:"));
  Serial.printf("Internal Free Heap %d\n", ESP.getFreeHeap());
  Serial.printf("Sketch Size %d, Free Sketch Space %d\n", ESP.getSketchSize(), ESP.getFreeSketchSpace());
  Serial.printf("Cpu Freq %d, SDK Version %s\n", ESP.getCpuFreqMHz(), ESP.getSdkVersion());
  Serial.printf("Flash Size %d, Flash Speed %d\n", ESP.getFlashChipSize(), ESP.getFlashChipSpeed());
  Serial.println("##################################\n");

  Serial.println("connect wifi");
  setup_wifi();
  Serial.println(WiFi.status());
  Serial.println("RSSI: " + WiFi.RSSI());
  Serial.println("IP: " + WiFi.localIP().toString());
  Serial.println("Gateway IP: " + WiFi.gatewayIP().toString());
  Serial.println("mac: " + WiFi.macAddress());
  digitalWrite(BUILTIN_LED, HIGH);

  if (!espClient.connected())
  {
    if (espClient.connect(tcp_server, 3000))
    {
      Serial.println("Client connected");
      espClient.write("{\"op\": \"upload\",\"topic\":\"Tiot_spneZhyC\",\"name\":\"dataset\",\"data\": \"李白,2,3,4\"}"); // Single char
      Serial.println("msg sent");
    }
  }
}

void loop()
{

  if (Serial.available() > 0)
  {
    reStr = Serial.readStringUntil('\n');
    // 检测json数据是否完整
    int jsonBeginAt = reStr.indexOf("{");
    int jsonEndAt = reStr.lastIndexOf("}");
    if (jsonBeginAt != -1 && jsonEndAt != -1)
    {
      reStr = reStr.substring(jsonBeginAt, jsonEndAt + 1);
      int str_len = reStr.length() + 1;
      char char_array[str_len];
      reStr.toCharArray(char_array, str_len);
      Serial.println(char_array);
    }
  }
}